import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    user: {},
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const rememberMe = userInfo.rememberMe
      userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          setToken(res.data, rememberMe)
          commit('SET_TOKEN', res.data)


          // // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
          // commit('SET_LOAD_MENUS', true)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      const avatar =require("@/assets/image/profile.jpg")
      commit('SET_NAME', "Admin")
      commit('SET_AVATAR', avatar)
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise(resolve => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', '')
          commit('SET_NAME', '')
          commit('SET_AVATAR', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })


      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
